// 工具

/**
 * 将时间解析为字符串
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime (time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

// 将事件戳转换为时间
export function toDate (v) {
  if (!v) return "";
  var time = new Date(v);
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();
  return (
    y +
    "-" +
    (m < 10 ? "0" + m : m) +
    "-" +
    (d < 10 ? "0" + d : d) +
    " " +
    (h < 10 ? "0" + h : h) +
    ":" +
    (mm < 10 ? "0" + mm : mm) +
    ":" +
    (s < 10 ? "0" + s : s)
  );
}

/**
 * 距离现在的时间 类似手机中的短信效果
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime (time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * 获取两个时间段之间有多少天
 * @param {string} fd
 * @param {string} sd
 * @returns {Object}
 */
export function getDateDif (fd, sd) {
  // 开始时间
  const firstDate = new Date(fd);
  // 结束时间
  const secondDate = new Date(sd);
  // const diff = Math.abs(firstDate.getTime() - secondDate.getTime());
  const diff = firstDate.getTime() - secondDate.getTime();
  // const result = parseInt(diff / (1000 * 60 * 60 * 24)); //小数点后面都不要  这里计算到 早上八点
  const result = Math.round(diff / (1000 * 60 * 60 * 24)); //四舍五入
  return result;
}

/**
 * 获取年月日
 * @returns {Object}
 */
export function formatDate (str) {
  const d = new Date();
  let month = "" + (d.getMonth() + 1);
  let day = "" + d.getDate();
  const year = d.getFullYear();
  if (month.length < 2) month = "0" + month;
  if (day.length < 2) day = "0" + day;
  return [year, month, day].join(str);
}

/**
 * 获取年月日 时分秒
 * @returns {Object}
 */
export function formatDate1 () {
  const d = new Date();
  let month = "" + (d.getMonth() + 1);
  let day = "" + d.getDate();
  const year = d.getFullYear();
  const hour = d.getHours() < 10 ? "0" + d.getHours() : d.getHours();
  const min = d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes();
  const sec = d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds();
  if (month.length < 2) month = "0" + month;
  if (day.length < 2) day = "0" + day;
  return year + "年" + month + "月" + day + "日" + hour + ":" + min + ":" + sec;
}

/**
 * 获取查询对象
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject (url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * 返回utf8字符串的字节长度
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength (str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

/**
 * 清除数组中的 假 内容
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray (actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

/**
 * 将 对象格式的 参数转换为 get请求的  a=1&b=2&c=3 的参数 直接加载请求地址上
 * @param {Object} json
 * @returns {Array}
 */
export function param (json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map((key) => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}

/**
 * 将地址栏中的 参数 https//abc.com?a=1&b=2&c=3 转换为 {a: "1", b: "2", c: "3"}
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj (url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text (val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

/**
 * 合并两个对象，给予最后一个优先级
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge (target, source) {
  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}

/**
 * 添加或者删除一个class  有就删除没有就添加 参照jquery
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass (element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += "" + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

/**
 * 获取当前时间 传参 start 后得到是 90 天前的 时间 时间戳
 * @param {string} type
 * @returns {Date}
 */
export function getTime (type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

//获取 n 天后的 日期 （N天）
export function getNewData (days) {
  var nDate = new Date();
  var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);
  var rDate = new Date(millSeconds);
  var year = rDate.getFullYear();
  var month = rDate.getMonth() + 1;
  if (month < 10)
    month = "0" + month;
  var date = rDate.getDate();
  if (date < 10) date = "0" + date;
  return (year + "-" + month + "-" + date);
}

// date 代表指定的日期，格式：2018-09-27
// day 传-1表始前一天，传1表始后一天
// JS获取指定日期的前一天，后一天
export function getNextDate (date, day) {
  var dd = new Date(date);
  dd.setDate(dd.getDate() + day);
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
  var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
  return y + "-" + m + "-" + d;
};


// 时间 - 工具
// 时间 - 工具
// var dateUtils = {
// 	UNITS: {
// 		'年': 31557600000,
// 		'月': 2629800000,
// 		'天': 86400000,
// 		'小时': 3600000,
// 		'分钟': 60000,
// 		'秒': 1000
// 	},
// 	//根据时间戳 判断 多少年前
// 	humanize: function(milliseconds) {
// 		var humanize = '';
// 		for (var key in this.UNITS) {
// 			if (milliseconds >= this.UNITS[key]) {
// 				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
// 				break;
// 			}
// 		}
// 		return humanize || '刚刚';
// 	},
// 	//转换时间格式
// 	format: function(dateStr) {
// 		var date = this.parse(dateStr)
// 		var diff = Date.now() - date.getTime();
// 		if (diff < this.UNITS['天']) {
// 			return this.humanize(diff);
// 		}
// 		var _format = function(number) {
// 			return (number < 10 ? ('0' + number) : number);
// 		};
// 		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
// 			_format(date.getHours()) + ':' + _format(date.getMinutes());
// 	},
// 	//将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
// 	parse: function(str) {
// 		var a = str.split(/[^0-9]/);
// 		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
// 	}
// };


export const date_utils = new DateUtilsAll()
//获取本周、本季度、本月、上月的开始日期、结束日期
// export function html2Text(val) {
function DateUtilsAll () {
  this.now = new Date(); //当前日期
  this.nowDayOfWeek = this.now.getDay(); //今天本周的第几天
  this.nowDay = this.now.getDate(); //当前日
  this.nowMonth = this.now.getMonth(); //当前月
  this.nowYear = this.now.getYear(); //当前年
  this.nowYear += (this.nowYear < 2000) ? 1900 : 0; //
  this.lastMonthDate = new Date(); //上月日期
  this.lastMonthDate.setDate(1);
  this.lastMonthDate.setMonth(this.lastMonthDate.getMonth() - 1);
  this.lastYear = this.lastMonthDate.getYear();
  this.lastMonth = this.lastMonthDate.getMonth();
}
//格式化日期：yyyy-MM-dd
DateUtilsAll.prototype.formatDate = function (date) {
  var myyear = date.getFullYear();
  var mymonth = date.getMonth() + 1;
  var myweekday = date.getDate();
  if (mymonth < 10) {
    mymonth = "0" + mymonth;
  }
  if (myweekday < 10) {
    myweekday = "0" + myweekday;
  }
  return (myyear + "-" + mymonth + "-" + myweekday);
}
//获得某月的天数
DateUtilsAll.prototype.getMonthDays = function (myMonth) {
  var monthStartDate = new Date(this.nowYear, myMonth, 1);
  var monthEndDate = new Date(this.nowYear, myMonth + 1, 1);
  var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
  return days;
}
// 获得本季度的开始月份
DateUtilsAll.prototype.getQuarterStartMonth = function () {
  var quarterStartMonth = 0;
  if (this.nowMonth < 3) {
    quarterStartMonth = 0;
  }
  if (2 < this.nowMonth && this.nowMonth < 6) {
    quarterStartMonth = 3;
  }
  if (5 < this.nowMonth && this.nowMonth < 9) {
    quarterStartMonth = 6;
  }
  if (this.nowMonth > 8) {
    quarterStartMonth = 9;
  }
  return quarterStartMonth;
}
//获得本周的开始日期
DateUtilsAll.prototype.getWeekStartDate = function () {
  var weekStartDate = new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek);
  return this.formatDate(weekStartDate);
}
// 本周开始日期 按周一 算第一天
DateUtilsAll.prototype.getWeekStartDate1 = function () {
  var weekStartDate = new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek + 1);
  return this.formatDate(weekStartDate);
}
//获得本周的结束日期
DateUtilsAll.prototype.getWeekEndDate = function () {
  var weekEndDate = new Date(this.nowYear, this.nowMonth, this.nowDay + (6 - this.nowDayOfWeek));
  return this.formatDate(weekEndDate);
}

//获得上周的开始日期
DateUtilsAll.prototype.getLastWeekStartDate = function () {
  var weekStartDate = new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek - 7);
  return this.formatDate(weekStartDate);
}
//获得上周的结束日期
DateUtilsAll.prototype.getLastWeekEndDate = function () {
  var weekEndDate = new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek - 1);
  return this.formatDate(weekEndDate);
}
//获得本月的开始日期
DateUtilsAll.prototype.getMonthStartDate = function () {
  var monthStartDate = new Date(this.nowYear, this.nowMonth, 1);
  return this.formatDate(monthStartDate);
}
//获得本月的结束日期
DateUtilsAll.prototype.getMonthEndDate = function () {
  var monthEndDate = new Date(this.nowYear, this.nowMonth, this.getMonthDays(this.nowMonth));
  return this.formatDate(monthEndDate);
}
//获得上月开始时间
DateUtilsAll.prototype.getLastMonthStartDate = function () {
  var lastMonthStartDate = new Date(this.nowYear, this.lastMonth, 1);
  return this.formatDate(lastMonthStartDate);
}
//获得上月结束时间
DateUtilsAll.prototype.getLastMonthEndDate = function () {
  var lastMonthEndDate = new Date(this.nowYear, this.lastMonth, getMonthDays(this.lastMonth));
  return this.formatDate(lastMonthEndDate);
}
//获得本季度的开始日期
DateUtilsAll.prototype.getQuarterStartDate = function () {
  var quarterStartDate = new Date(this.nowYear, this.getQuarterStartMonth(), 1);
  return this.formatDate(quarterStartDate);
}
//或的本季度的结束日期
DateUtilsAll.prototype.getQuarterEndDate = function () {
  var quarterEndMonth = this.getQuarterStartMonth() + 2;
  var quarterStartDate = new Date(this.nowYear, this.quarterEndMonth,
    this.getMonthDays(quarterEndMonth));
  return this.formatDate(quarterStartDate);
}

/**
 *
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function (...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

/**
 * 这只是深度复制的一个简单版本
 * 有很多边缘情况的bug
 * 如果你想使用一个完美的深度拷贝，使用lodash的_.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone (source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 * 数组去重
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr (arr) {
  return Array.from(new Set(arr));
}

/**
 * 创建一个 32 进制 唯一的字符串
 * @returns {string}
 */
export function createUniqueString () {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}

/**
 * 检查元素是否包含一个 class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass (ele, cls) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * 新增 class
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass (ele, cls) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * 删除class
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass (ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = "id", pid = "parentId") {
  var res = [];
  var temp = {};
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i];
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]["children"]) {
        temp[data[k][pid]]["children"] = [];
      }
      if (!temp[data[k][pid]]["_level"]) {
        temp[data[k][pid]]["_level"] = 1;
      }
      data[k]["_level"] = temp[data[k][pid]]._level + 1;
      temp[data[k][pid]]["children"].push(data[k]);
    } else {
      res.push(data[k]);
    }
  }
  return res;
}
export function treeDataTranslateList (data, id = "id", pid = "parentId") {
  var res = [];
  var temp = {};
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i];
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]["list"]) {
        temp[data[k][pid]]["list"] = [];
      }
      if (!temp[data[k][pid]]["_level"]) {
        temp[data[k][pid]]["_level"] = 1;
      }
      data[k]["_level"] = temp[data[k][pid]]._level + 1;
      temp[data[k][pid]]["list"].push(data[k]);
    } else {
      res.push(data[k]);
    }
  }
  return res;
}

/**
 * 获取一个 UUID
 * @returns {string}
 */
export function getUuid () {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 32; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4";
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  s[8] = s[13] = s[18] = s[23] = "-";

  this.uuidA = s.join("");
  console.log(s.join(""), 's.join("")');
  return this.uuidA;
}

/**
 * 获取uuid
 */
export function getUUID () {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    return (c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8").toString(
      16
    );
  });
}

/**
 * 判断浏览器类型
 * @returns {string}
 */
export function myBrowser () {
  var userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
  var isOpera = userAgent.indexOf("Opera") > -1; // 判断是否Opera浏览器
  var isIE =
    userAgent.indexOf("compatible") > -1 &&
    userAgent.indexOf("MSIE") > -1 &&
    !isOpera; // 判断是否IE浏览器
  var isEdge = userAgent.indexOf("Edge") > -1; // 判断是否IE的Edge浏览器
  var isFF = userAgent.indexOf("Firefox") > -1; // 判断是否Firefox浏览器
  var isSafari =
    userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; // 判断是否Safari浏览器
  var isChrome =
    userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; // 判断Chrome浏览器

  if (isIE) {
    var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
    reIE.test(userAgent);
    var fIEVersion = parseFloat(RegExp["$1"]);
    if (fIEVersion == 7) {
      return "IE7";
    } else if (fIEVersion == 8) {
      return "IE8";
    } else if (fIEVersion == 9) {
      return "IE9";
    } else if (fIEVersion == 10) {
      return "IE10";
    } else if (fIEVersion == 11) {
      return "IE11";
    } else {
      return "0";
    } // IE版本过低
    return "IE";
  }
  if (isOpera) {
    return "Opera";
  }
  if (isEdge) {
    return "Edge";
  }
  if (isFF) {
    return "FF";
  }
  if (isSafari) {
    return "Safari";
  }
  if (isChrome) {
    return "Chrome";
  }
}

/**
 * 空值判断
 * @param {*} value
 * @param {string} run
 * @returns {string}
 */
export function dataNull (value, run = "--") {
  if (
    value === null ||
    value === "" ||
    value === undefined ||
    value !== value ||
    isNaN(value)
  ) {
    return run;
  } else {
    return value;
  }
}

export function millsToTime (mills) {
  if (!mills) {
    return "";
  }
  const s = mills / 1000;
  if (s < 60) {
    return s.toFixed(0) + " 秒";
  }
  const m = s / 60;
  if (m < 60) {
    return m.toFixed(0) + " 分钟";
  }
  const h = m / 60;
  if (h < 24) {
    return h.toFixed(0) + " 小时";
  }
  const d = h / 24;
  if (d < 30) {
    return d.toFixed(0) + " 天";
  }
  const month = d / 30;
  if (month < 12) {
    return month.toFixed(0) + " 个月";
  }
  const year = month / 12;
  return year.toFixed(0) + " 年";
}


//获取两个数字之间的随机整数 含最小 和 最大
function getRandomInt (min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //不含最大值，含最小值
}
export function getOffsetTopToScrollParent(element, scrollParent) {
  let offsetTop = element.offsetTop;
  let offsetLeft = element.offsetLeft;

  let currentElement = element.offsetParent;

  while (currentElement && currentElement !== scrollParent) {
    offsetTop += currentElement.offsetTop;
    offsetLeft += currentElement.offsetLeft;
    currentElement = currentElement.offsetParent;
  }

  return { top: offsetTop, left: offsetLeft };
}
